package com.un.ebs.sys.uitl;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author linyuan
 * @date 2019/6/25
 */
public class MD5Util {

    private final static String MODE = "MD5";

    public final static String md5Signature(String data) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(MODE);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md.update(data.getBytes(StandardCharsets.UTF_8));
        byte[] digestByte = md.digest();
        return byte2hex(digestByte);
    }

    private final static String byte2hex(byte[] b) {
        StringBuilder buffer = new StringBuilder();
        String stmp = "";
        for (int i = 0; i < b.length; i++) {
            stmp = Integer.toHexString(b[i] & 0xFF);
            if (stmp.length() == 1) {
                buffer.append("0" + stmp);
            } else {
                buffer.append(stmp);
            }
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        System.out.println(MD5Util.md5Signature("TC"));
    }
}
